package com.mashuai.utils.toolkit.core.msConverts;

import com.mashuai.utils.toolkit.achieve.MsExegesis;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

import java.beans.PropertyDescriptor;
import java.util.HashSet;
import java.util.Set;

/**
 * @ClassName: MsBeanUtils
 * @Author : mashuai
 * @Description: TODO
 */
@MsExegesis("实体类拷贝工具")
public class MsBeanUtils {
    /****
     *只拷贝属性值，包含null
     * @param source
     * @return
     */
    @MsExegesis("只拷贝属性值，包含null")
    public static void copyProperties(Object source, Object target) {
        BeanUtils.copyProperties(source, target);
    }

    /****
     *只拷贝不为null的属性值
     * @param source
     * @return
     */
    @MsExegesis("只拷贝不为null的属性值")
    public static void copyPropertiesIgnoreNull(Object source, Object target) {
        BeanUtils.copyProperties(source, target, getNullPropertyNames(source, false));
    }

    /****
     *只拷贝不为null或者不为""的属性值
     * @param source
     * @return
     */
    @MsExegesis("只拷贝不为null或者不为 '' 的属性值")
    public static void copyPropertiesIgnoreNullAndEmptyStr(Object source, Object target) {
        BeanUtils.copyProperties(source, target, getNullPropertyNames(source, true));
    }

    /****
     *只拷贝不为null。或不为""的属性值
     * @param source
     * @param ingoreEmptyStr true拷贝时候，忽略值为null或""的属性值
     * @return
     */
    private static String[] getNullPropertyNames(Object source, Boolean ingoreEmptyStr) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        PropertyDescriptor[] pds = src.getPropertyDescriptors();
        Set<String> emptyNames = new HashSet<>();
        for (PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            if (ingoreEmptyStr) {
                if (srcValue == null || "".equals(String.valueOf(srcValue))) emptyNames.add(pd.getName());
            } else {
                if (srcValue == null) emptyNames.add(pd.getName());
            }
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }


}
